<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/4/10
 * Time: 12:01
 */

namespace plugin\admin\app\logic\plan;


use app\exception\IndexException;
use plugin\admin\app\logic\BaseLogic;
use plugin\admin\app\model\font\FontModel;
use plugin\admin\app\model\image\ImageModelModel;
use plugin\admin\app\model\novel\NovelChapterModel;
use plugin\admin\app\model\novel\NovelChapterPartModel;
use plugin\admin\app\model\novel\NovelSpreadModel;
use plugin\admin\app\model\plan\BackgroundMusicModel;
use plugin\admin\app\model\plan\PromotionPlanModel;
use plugin\admin\app\model\moyin\TimbreModel;
use support\Request;
use support\Response;
use support\Db;

class PlanLogic extends BaseLogic
{
    protected static $instance;

    public function __construct()
    {
        $this->model = new PromotionPlanModel();
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }

        return new self();
    }

    public function select(Request $request): Response
    {
        // 小说上下架筛选
        $novel_spread_status = $request->input('novel_spread_status', '');
        if($novel_spread_status !== ''){
            // 获取所有的上架小说的novel_sn
            $novel_sn_sql = "
                ( SELECT novel_sn FROM video_novel_spread WHERE spread_type = 1 AND task_status = 2 AND isdel = 0 ) UNION
                ( SELECT novel_sn FROM video_novel_spread WHERE spread_type = 2 AND under_status = 1 AND isdel = 0 ) UNION
                ( SELECT novel_sn FROM video_novel_spread WHERE spread_type = 3 AND `status` = 1 AND isdel = 0 )
            ";
            $active_novel_spread = Db::select($novel_sn_sql);
            if($active_novel_spread && count($active_novel_spread) > 0){
                $novel_spread_arr = [];
                foreach($active_novel_spread as $ansv){
                    $novel_spread_arr[] = $ansv->novel_sn;
                }
                if($novel_spread_status == 1){
                    $request->inputSet('novel_sn', ['in', implode(',', $novel_spread_arr)]);
                }else{
                    $request->inputSet('novel_sn', ['not in', implode(',', $novel_spread_arr)]);
                }
            }else{
                if($novel_spread_status == 1){ // 没有上架小说的情况
                    $request->inputSet('novel_sn', 0);
                }
            }
        }
        // 优秀案例筛选
        $is_example = $request->input('is_example', '');
        if($is_example !== ''){
            // 获取所有的设置为优秀案例的ID
            $example_plan = Db::table('video_user_promotion_plan')->select('planid')->where(['is_example' => 1, 'isdel' => 0])->groupBy('planid')->get();
            if($example_plan && count($example_plan) > 0){
                $planid_arr = [];
                foreach($example_plan as $epv){
                    $planid_arr[] = $epv->planid;
                }
                if($is_example == 1){
                    $request->inputSet('id', ['in', implode(',', $planid_arr)]);
                }else{
                    $request->inputSet('id', ['not in', implode(',', $planid_arr)]);
                }
            }else{
                if($is_example == 1){ // 没有优秀案例的情况
                    $request->inputSet('id', 0);
                }
            }
        }
        $field = $request->input('field');
        if($field==false){
            $request->inputSet('field','created_at');
            $request->inputSet('order','desc');
        }

        $request->inputSet('isdel','0');
        // dump($request->all());
        return parent::select($request);
    }

    protected function formatNormal($items, $total): Response
    {
        $novelMap = $this->getListMapById(NovelSpreadModel::getInstance(),$items,'novel_sn','novel_sn');
        $chapterMap = $this->getListMapById(NovelChapterModel::getInstance(),$items,'chapterid','id');
        $musicMap = $this->getListMapById(BackgroundMusicModel::getInstance(),$items,'musicid','id');
        $timbreMap = $this->getListMapById(TimbreModel::getInstance(),$items,'timbreid','id');
        $fontMap = $this->getListMapById(FontModel::getInstance(),$items,'fontid','id');
        $modelMap = $this->getListMapById(ImageModelModel::getInstance(),$items,'modelid','id');
        foreach($items as &$val){
            $val['title'] = isset($novelMap[$val['novel_sn']])?$novelMap[$val['novel_sn']]['title']:$val['novel_sn'];
            $val['content'] = isset($chapterMap[$val['chapterid']])?$chapterMap[$val['chapterid']]['content']:$val['chapterid'];

            $val['musicname'] = isset($musicMap[$val['musicid']])?$musicMap[$val['musicid']]['name']:$val['musicid'];
            $val['music_url'] = isset($musicMap[$val['musicid']])?$musicMap[$val['musicid']]['music_url']:'';

            $val['fontname'] = isset($fontMap[$val['fontid']])?$fontMap[$val['fontid']]['name']:$val['fontid'];
            $val['modelname'] = isset($modelMap[$val['modelid']])?$modelMap[$val['modelid']]['name']:$val['modelid'];

            $val['timbrename'] = isset($timbreMap[$val['timbreid']])?
                                 $timbreMap[$val['timbreid']]['name'].'('.$timbreMap[$val['timbreid']]['scenes'].')':$val['timbreid'];

        }
        return parent::formatNormal($items, $total);
    }

    public function insert(Request $request): Response
    {
        $request->inputSet('status',0);
        return parent::insert($request);
    }

    protected function doInsert(array $data)
    {
        $data['novel_sn'] = NovelChapterModel::getInstance()->getWhere(['id'=>$data['chapterid']])->value('novel_sn');
        $data['spread_type'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('spread_type');
        $id = parent::doInsert($data);
//        if($id){
//            //生成唯一的请求id
//            $requestId = md5(round(microtime(true)*1000).uniqid().mt_rand(1000,9999));
//
//            // 队列名
//            $queue = 'asyncPlanPart';
//            // 数据，可以直接传数组，无需序列化
//            $data = ['requestid'=>$requestId,'planid'=>$id];
//            // 投递消息
//            RedisQueue::getInstance()->sendQueue($queue, $data);
//        }
        return $id;
    }

    public function update(Request $request): Response
    {
        return parent::update($request);
    }

    protected function doUpdate($id, $data)
    {
        if(!empty($data['chapterid'])){
            $data['novel_sn'] = NovelChapterModel::getInstance()->getWhere(['id'=>$data['chapterid']])->value('novel_sn');
            $data['spread_type'] = NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$data['novel_sn']])->value('spread_type');
        }

        return parent::doUpdate($id, $data);
    }

    public function delete(Request $request): Response
    {
        return parent::isDelete($request);
    }

    public function doIsDelete($ids)
    {
        parent::doIsDelete($ids);

        foreach ($ids as $id){
            $novelSn = $this->model->where(['id'=>$id])->value('novel_sn');
            $planNums = $this->model->getWhere(['id'=>$id,'isdel'=>0])->count();
            NovelSpreadModel::getInstance()->getWhere(['novel_sn'=>$novelSn])->update(['plan_nums'=>$planNums]);
        }
    }

    public function copy(Request $request): Response
    {
        $first = $this->model->find($request->input('id'));
        if($first==false){
            throw new IndexException(4020,'方案不存在');
        }
        $insert = $first->toArray();
        unset($insert['id'],$insert['created_at'],$insert['updated_at']);
        $insert['name'] = $insert['name'].'-复制';
        $insert['status'] = '0';
        $insert['create_way'] = 'copy';
        $planid = $this->model->insertGetId($insert);

        if($planid){
            $batch = NovelChapterPartModel::getInstance()->getWhere(['planid'=>$first['id'],'isdel'=>0])->max('batch');
            $partsData = NovelChapterPartModel::getInstance()->getWhere(['planid'=>$first['id'],'batch'=>$batch,'isdel'=>0])->get()->toArray();

            $insertParts = [];
            $batch = date('ymdHis').mt_rand(10,99);
            foreach($partsData as &$val){
                unset($val['id'],$val['planid'],$val['batch'],$val['created_at'],$val['updated_at']);
                $val['planid'] = $planid;
                $val['batch'] = $batch;
                $insertParts[] =$val;
            }
            NovelChapterPartModel::getInstance()->insert($insertParts);
        }

        return $this->json(0);
    }
}